package com.hengtongxing.hejiayun.mine;


import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.hengtongxing.hejiayun.R;
import com.hengtongxing.hejiayun.base.BaseActivity;
import com.hengtongxing.hejiayun.base.DataCallBack;
import com.hengtongxing.hejiayun.bean.AddressListBean;
import com.hengtongxing.hejiayun.bean.BaseResponseBean;
import com.hengtongxing.hejiayun.bean.JsonBean;
import com.hengtongxing.hejiayun.event.AddressEvent;
import com.hengtongxing.hejiayun.mine.model.IMineModel;
import com.hengtongxing.hejiayun.mine.model.MineModelImpl;
import com.hengtongxing.hejiayun.utils.GetJsonDataUtil;
import com.hengtongxing.hejiayun.utils.ToastUtil;
import com.hengtongxing.hejiayun.widget.AppTitleBar;
import com.hengtongxing.hejiayun.widget.ViewLoading;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddAddressActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.edit_name)
    EditText editName;
    @BindView(R.id.edit_mobile)
    EditText editMobile;
    @BindView(R.id.tv_select_address)
    TextView tvSelectAddress;
    @BindView(R.id.edit_details_address)
    EditText editDetailsAddress;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.ll_select_address)
    LinearLayout llSelectAddress;
    @BindView(R.id.ll_all_address)
    LinearLayout llAllAddress;
    private String provienceName = "";
    private String provienceCode;
    private String cityName = "";
    private String cityCode;
    private String areaName = "";
    private String areaCode;

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<JsonBean.CityBean>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<JsonBean.CityBean.AreaBean>>> options3Items = new ArrayList<>();
    private Thread thread;
    private IMineModel mineModel;
    private AddressListBean.DataBean.ItemListBean dataBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_address);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        dataBean = (AddressListBean.DataBean.ItemListBean) getIntent().getSerializableExtra("DataBean");
        mineModel = new MineModelImpl();
        // 子线程中解析省市区数据
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                initJsonData();
            }
        });
        thread.start();

        if (dataBean != null) {
            editName.setText(dataBean.getName());
            if (!TextUtils.isEmpty(dataBean.getName())) {
                editName.setSelection(dataBean.getName().length());
            }
            editMobile.setText(dataBean.getMobile());
            if (!TextUtils.isEmpty(dataBean.getMobile())) {
                editMobile.setSelection(dataBean.getMobile().length());
            }
            editDetailsAddress.setText(dataBean.getAddress());
            if (!TextUtils.isEmpty(dataBean.getAddress())) {
                editDetailsAddress.setSelection(dataBean.getAddress().length());
            }
            provienceName = dataBean.getProvince();
            cityName = dataBean.getCity();
            areaName = dataBean.getArea();
            String tx = provienceName + " " + cityName + " " + areaName;
            tvSelectAddress.setText(tx);
        }
    }


    @OnClick({R.id.ll_select_address, R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_select_address:
                showPickerView();
                break;
            case R.id.tv_commit:
                addAddress();
                break;
        }
    }

    public void addAddress() {
        String name = editName.getText().toString();
        String mobile = editMobile.getText().toString();
        String address = editDetailsAddress.getText().toString();

        if (TextUtils.isEmpty(name)) {
            ToastUtil.showShort("请输入收货人");
            return;
        }
        if (TextUtils.isEmpty(mobile)) {
            ToastUtil.showShort("请输入手机号码");
            return;
        }

        if (dataBean == null) {
            if (TextUtils.isEmpty(provienceName) || TextUtils.isEmpty(cityName) || TextUtils.isEmpty(areaName)) {
                ToastUtil.showShort("请选择所在区域");
                return;
            }
        }

        if (TextUtils.isEmpty(address)) {
            ToastUtil.showShort("请输入详细地址");
            return;
        }
        ViewLoading.showProgress(mActivity, "提交中......");
        if (dataBean == null) {
            mineModel.requestAddressAdd(name, mobile, provienceName, cityName, areaName, address, new DataCallBack<BaseResponseBean>() {
                @Override
                public void onSuccessful(BaseResponseBean bean) {
                    ToastUtil.showShort(bean.getMsg());
                    EventBus.getDefault().post(new AddressEvent());
                    finish();
                }

                @Override
                public void onFailed(String msg, String code) {

                }
            });
        } else {
            mineModel.requestAddressEdit(dataBean.getId() + "", name, mobile, provienceName, cityName, areaName, address, new DataCallBack<BaseResponseBean>() {
                @Override
                public void onSuccessful(BaseResponseBean bean) {
                    ToastUtil.showShort(bean.getMsg());
                    EventBus.getDefault().post(new AddressEvent());
                    finish();
                }

                @Override
                public void onFailed(String msg, String code) {

                }
            });
        }

    }

    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                if (options1Items.size() > 0) {
                    provienceName = options1Items.get(options1).getPickerViewText();
                    provienceCode = options1Items.get(options1).getCode();
                } else {
                    provienceName = "";
                    provienceCode = "";
                }

                if (options2Items.get(options1).size() > 0) {
                    cityName = options2Items.get(options1).get(options2).getPickerViewText();
                    cityCode = options2Items.get(options1).get(options2).getCode();
                } else {
                    cityName = "";
                    cityCode = "";
                }

                if (options3Items.get(options1).get(options2).size() > 0) {
                    areaName = options3Items.get(options1).get(options2).get(options3).getPickerViewText();
                    areaCode = options3Items.get(options1).get(options2).get(options3).getCode();
                } else {
                    areaName = "";
                    areaCode = "";
                }

                //返回的分别是三个级别的选中位置
                String tx = provienceName + " " + cityName + " " + areaName;
                tvSelectAddress.setText(tx);
            }
        }).setTitleText("")
                .setTitleSize(16)
                .setSubmitColor(getResources().getColor(R.color.text_color_2))//确定按钮文字颜色
                .setSubCalSize(16)
                .setCancelColor(getResources().getColor(R.color.text_color_2))//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(R.color.white))
                .setDividerColor(getResources().getColor(R.color.line_color_gray))
                .setTextColorCenter(getResources().getColor(R.color.text_color_2))
                .setContentTextSize(18)
                .setLineSpacingMultiplier(2)
                .isDialog(true)
                .build();

        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器

        Dialog mDialog = pvOptions.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvOptions.getDialogContainerLayout().setLayoutParams(params);

            Window window = mDialog.getWindow();
            if (window != null) {
                window.setWindowAnimations(R.style.picker_view_slide_anim);//修改动画样式
                window.getDecorView().setPadding(0, 0, 0, 0);
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                lp.gravity = Gravity.BOTTOM;
            }
        }
        pvOptions.show();

        int option1 = 0;
        int option2 = 0;
        int option3 = 0;
        if (!TextUtils.isEmpty(provienceName) && !TextUtils.isEmpty(cityName) && !TextUtils.isEmpty(areaName)) {
            for (int i = 1; i < options1Items.size(); i++) {
                if (provienceName.equals(options1Items.get(i).getName())) {
                    option1 = i;
                    for (int j = 0; j < options1Items.get(option1).getCitylist().size(); j++) {
                        if (cityName.equals(options1Items.get(option1).getCitylist().get(j).getName())) {
                            option2 = j;
                            for (int k = 0; k < options1Items.get(option1).getCitylist().get(option2).getArealist().size(); k++) {
                                if (areaName.equals(options1Items.get(option1).getCitylist().get(option2).getArealist().get(k).getName())) {
                                    option3 = k;
                                    break;
                                }
                            }

                        }
                    }
                }
            }
        }
        pvOptions.setSelectOptions(option1, option2, option3);
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(mActivity, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<JsonBean.CityBean> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<JsonBean.CityBean.AreaBean>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三级）

            for (int c = 0; c < jsonBean.get(i).getCitylist().size(); c++) {//遍历该省份的所有城市
                CityList.add(jsonBean.get(i).getCitylist().get(c));//添加城市
                ArrayList<JsonBean.CityBean.AreaBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCitylist().get(c).getArealist() == null || jsonBean.get(i).getCitylist().get(c).getArealist().size() == 0) {
                    City_AreaList.add(new JsonBean.CityBean.AreaBean());
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCitylist().get(c).getArealist());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

}
